#include "head.h"

int lsCommand(command_t* task, int fd, MYSQL* mysql,char* user_id) {
    if (task->types == LS) {
        char f_buf[1000] = {0};
        off_t f_len = 0;
        memset(f_buf, 0, sizeof(f_buf));
printf("bufore!\n");
        recv(fd, &f_len, sizeof(off_t), MSG_WAITALL);
        recv(fd, f_buf, f_len, MSG_WAITALL);
printf("bufore!\n");
        printf("f_buf:%s\n",f_buf);
        // SQL 查询
        char sql_buf[1024] = "SELECT file_name FROM file WHERE Parent_dir_id = (SELECT file_id FROM file WHERE path = ? AND user_id = ?) AND `delete` = 0";

        // 设置预处理的 SQL
        MYSQL_STMT *stmt = mysql_stmt_init(mysql);
        mysql_stmt_prepare(stmt, sql_buf, strlen(sql_buf));
printf("here!\n");

        // 绑定参数
        MYSQL_BIND bind[2];
        memset(bind, 0, sizeof(bind));
        bind[0].buffer_type = MYSQL_TYPE_STRING;
        bind[0].buffer = (char *)f_buf;
        bind[0].buffer_length = strlen(f_buf) + 1; // 包含结束符
        
        bind[1].buffer_type = MYSQL_TYPE_STRING;
        bind[1].buffer = (char *)user_id;
        bind[1].buffer_length = strlen(user_id) + 1; // 包含结束符
        mysql_stmt_bind_param(stmt, bind);

        // 执行查询
        if (mysql_stmt_execute(stmt)) {
            printf("Error: %s\n", mysql_stmt_error(stmt));
            mysql_stmt_close(stmt);
            return -1;
        }

        // 绑定结果集
        MYSQL_BIND bind_result;
        char result_column[60];
        memset(&bind_result, 0, sizeof(bind_result));
        bind_result.buffer_type = MYSQL_TYPE_STRING;
        bind_result.buffer = result_column;
        bind_result.buffer_length = sizeof(result_column);
        mysql_stmt_bind_result(stmt, &bind_result);

        // 获取并发送查询结果
        while (mysql_stmt_fetch(stmt) == 0) {
            // 发送文件名
            send(fd, result_column, strlen(result_column), 0);
            // 发送换行符
            send(fd, "\n", 1, 0);
        }

        // 发送结束标记
        send(fd, "END_OF_LS", 9, 0);
        mysql_stmt_close(stmt);
    }

    return 0;
}


